package net.easyjava.framework.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.api.domain.Job;
import com.aliyun.oss.model.PartETag;
import net.easyjava.framework.BaseController;
import net.easyjava.framework.constants.EJConstants;
import net.easyjava.framework.third.aliyun.AliyunOSSUtils;
import net.easyjava.framework.third.aliyun.AliyunTransUtils;
import net.easyjava.tools.model.ModelBean;
import net.easyjava.tools.model.ModelConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
public class EJController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(EJController.class);

	/**
	 * 完成分片上传
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(EJConstants.SLICE_UPLOAD_JSON)
	@ResponseBody
	public ModelBean sliceUpload(
			@RequestParam String key,
			@RequestParam String uploadId,
			@RequestParam String bucket,
			@RequestParam int partSize,
			HttpServletRequest request, HttpServletResponse response) {
		long begin = System.currentTimeMillis();
		//检查接口安全性
		ModelBean modelBean = new ModelBean();
		try {
			List<PartETag> partETagList = AliyunOSSUtils.getMultiParts(bucket, uploadId, key);
			if(partETagList.size() == partSize){
				AliyunOSSUtils.uploadMulti(bucket,uploadId,partETagList,key);
				JSONObject json = new JSONObject();
				json.put("key",key);
				modelBean = new ModelBean(json);
			}else{
				modelBean = new ModelBean("分片还没有上传完成");
			}
		}catch (Exception e){
			logger.error(e.getMessage(),e.fillInStackTrace());
			modelBean = new ModelBean(ModelConstants.MESSAGE_ERROR);
		}
		return model(modelBean,begin, request, response);
	}

	/**
	 * 上传分片
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(EJConstants.SLICE_UPLOAD_PART_JSON)
	@ResponseBody
	public ModelBean sliceUploadPart(
            @RequestParam String bucket,
            @RequestParam String key,
            @RequestParam String uploadId,
            @RequestParam int total,
            @RequestParam int index,
			HttpServletRequest request, HttpServletResponse response) {
		long begin = System.currentTimeMillis();
		//检查接口安全性
		ModelBean modelBean = new ModelBean();
		try {
			// 转型为MultipartHttpRequest：
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			// 获得文件：
			MultiValueMap<String, MultipartFile> multiValueMap = multipartRequest.getMultiFileMap();
			Set<Map.Entry<String,List<MultipartFile>>> set = multiValueMap.entrySet();
			for(Map.Entry<String,List<MultipartFile>> map:set){
				List<MultipartFile> fileList = map.getValue();
				for(MultipartFile file:fileList){
					InputStream is = file.getInputStream();
					long size = file.getSize();
                    PartETag partETag = AliyunOSSUtils.uploadMultiPart(bucket, uploadId, is, size, index, key);
//
				}
			}

			JSONObject json = new JSONObject();
			json.put("key",key);
			modelBean = new ModelBean(json);
		}catch (Exception e){
			logger.error(e.getMessage(),e.fillInStackTrace());
			modelBean = new ModelBean(ModelConstants.MESSAGE_ERROR);
		}
		return model(modelBean,begin, request, response);
	}

	/**
	 * 获取上传id
	 * @param key
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(EJConstants.GET_SLICE_UPLOAD_ID_JSON)
	@ResponseBody
	public ModelBean getSliceUploadId(
			@RequestParam String bucket,
			@RequestParam String key,
			HttpServletRequest request, HttpServletResponse response) {
		//检查接口安全性
		ModelBean modelBean = new ModelBean();
		try {
            String uploadId = AliyunOSSUtils.getMultiUploadId(bucket, key);
			JSONObject data = new JSONObject();
			data.put("uploadId",uploadId);
			data.put("key",key);
			modelBean = new ModelBean(data);
		}catch (Exception e){
			logger.error(e.getMessage(),e.fillInStackTrace());
			modelBean = new ModelBean(ModelConstants.MESSAGE_ERROR);
		}
		return model(modelBean, request, response);
	}


	/**
	 * 提交转码任务
	 * @param inBucket
	 * @param inKey
	 * @param outBucket
	 * @param outKey
	 * @param pipelinId 管道id
	 * @param templateId 模板id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(EJConstants.SUBMIT_TRANS_JOB_JSON)
	@ResponseBody
	public ModelBean submitTransJob(
			@RequestParam String inBucket,
			@RequestParam String inKey,
			@RequestParam String outBucket,
			@RequestParam String outKey,
			@RequestParam String pipelinId,
			@RequestParam String templateId,
			HttpServletRequest request, HttpServletResponse response) {
		//检查接口安全性
		ModelBean modelBean = new ModelBean();
		try {
			Job job = AliyunTransUtils.submitBJJob(inBucket, inKey, outBucket, outKey, pipelinId, templateId);
			if(job == null){
				modelBean = new ModelBean("转码失败");
			}else{
				modelBean = new ModelBean(job);
			}
		}catch (Exception e){
			logger.error(e.getMessage(),e.fillInStackTrace());
			modelBean = new ModelBean(ModelConstants.MESSAGE_ERROR);
		}
		return model(modelBean, request, response);
	}


	/**
	 * 查询转码任务列表
	 * @param jobIds
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(EJConstants.QUERY_TRANS_JOB_LIST_JSON)
	@ResponseBody
	public ModelBean queryTransJobList(
			@RequestParam String jobIds,
			HttpServletRequest request, HttpServletResponse response) {
		//检查接口安全性
		ModelBean modelBean = new ModelBean();
		try {
			List<Job> jobs = AliyunTransUtils.queryBJJobList(jobIds);
			modelBean = new ModelBean(jobs);
		}catch (Exception e){
			logger.error(e.getMessage(),e.fillInStackTrace());
			modelBean = new ModelBean(ModelConstants.MESSAGE_ERROR);
		}
		return model(modelBean, request, response);
	}




}
